<route lang="json5">
{
  style: {
    navigationStyle: 'default',
    navigationBarTitleText: '我的订单',
  },
}
</route>
<template>
  <view class="order-list-page min-h-screen bg-gray-50">
    <view class="bg-white sticky z-10 shadow-sm">
      <view class="tab-container overflow-x-auto">
        <view class="flex border-b">
          <view
            v-for="(tab, index) in orderTabs"
            :key="index"
            class="px-4 py-3 text-sm font-medium whitespace-nowrap flex-1 text-center relative"
            :class="queryParams.status === tab.status ? 'text-orange-500' : 'text-gray-600'"
            @click="setActiveTab(tab.status)"
          >
            {{ tab.label }}
            <view
              v-if="queryParams.status === tab.status"
              class="absolute bottom-0 left-0 right-0 h-0.5 bg-orange-500"
            ></view>
          </view>
        </view>
      </view>
    </view>

    <!-- Order List -->
    <view class="p-4">
      <wd-status-tip image="search" tip="暂无订单" v-if="filteredOrders.length == 0" />

      <view v-else class="space-y-4">
        <view
          v-for="(order, index) in filteredOrders"
          :key="index"
          class="bg-white rounded-lg shadow-sm overflow-hidden"
        >
          <!-- Order Header -->
          <view class="p-3 border-b border-gray-100 flex justify-between items-center">
            <view class="flex items-center">
              <text class="text-xs text-gray-500">
                <text v-if="order.orderType == 1" class="text-[#ff6a00]">商品</text>
                <text v-if="order.orderType == 2" class="text-[#ff6a00]">拼团</text>
                <text v-if="order.orderType == 3" class="text-[#ff6a00]">家政</text>
                <text v-if="order.orderType == 4" class="text-[#ff6a00]">大转盘</text>
                订单编号：{{ order.orderId }}
              </text>
            </view>
            <text
              class="text-sm font-medium"
              :class="{
                'text-orange-500': order.status === 0,
                'text-blue-500': order.status === 1,
                'text-green-500': order.status === 3,
                'text-green-500': order.status === 4,
                'text-purple-500': order.status === 5,
              }"
            >
              {{ parseStatus(order.status) }}
            </text>
          </view>

          <view class="p-3 flex" @click="openOrderDetail(order)">
            <view class="relative" @click.stop="openImagePreview(order.productImage)">
              <image
                :src="order.productImage"
                :alt="order.productName"
                class="w-20 h-20 object-cover rounded-md"
              />
              <view
                class="absolute -bottom-1 -right-1 bg-gray-800/70 text-white text-xs px-1.5 py-0.5 rounded-full"
              >
                x{{ order.totalNum }}
              </view>
            </view>

            <!-- Order Info -->
            <view class="ml-3 flex-1">
              <view class="font-medium text-gray-800 line-clamp-2">{{ order.productName }}</view>

              <view class="mt-1 flex justify-between items-baseline">
                <view>
                  <text class="text-sm text-gray-500">¥{{ order.totalPrice }}</text>
                </view>
              </view>

              <view class="mt-1 flex justify-end items-baseline">
                <view class="text-sm font-medium">
                  <text class="text-gray-500">合计：</text>
                  <text class="text-orange-500">¥{{ order.totalPrice }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="px-3 text-xs text-gray-500">
            <text>下单时间：{{ order.createTime }}</text>
          </view>

          <view v-if="order.verificationTime" class="px-3 mb-2 mt-1 text-xs text-gray-500">
            核销时间：{{ order.verificationTime }}
          </view>

          <view
            class="p-3 border-t border-gray-100 flex justify-end"
            v-if="[0, 1, 3, 4, 5].includes(order.status)"
          >
            <wd-button
              size="small"
              type="primary"
              v-if="parseCanVerification(order)"
              class="px-4 py-1.5 border border-blue-500 text-blue-500 rounded-full text-sm"
              @click="handleVerification(order)"
              custom-class="mx-1!"
            >
              核销
            </wd-button>

            <wd-button
              size="small"
              type="primary"
              v-if="order.status == 3"
              class="px-4 py-1.5 bg-orange-500 text-white rounded-full text-sm"
              @click="openOrderComment(order)"
              custom-class="mx-1!"
            >
              去评价
            </wd-button>

            <!-- <wd-button
              size="small"
              type="warning"
              v-if="order.status == 1 && order.orderType != 4"
              @click="openCancelOrder(order)"
              class="px-4 py-1.5 border border-gray-400 text-gray-500 rounded-full text-sm"
              custom-class="mx-1!"
            >
              退款
            </wd-button> -->

            <wd-button
              size="small"
              type="warning"
              v-if="order.status == 0 && order.orderType != 4"
              @click="handlePay(order)"
              class="px-4 py-1.5 border border-gray-400 text-gray-500 rounded-full text-sm"
              custom-class="mx-1!"
            >
              支付
            </wd-button>

            <wd-button
              size="small"
              type="primary"
              v-if="order.status == 4"
              @click="checkTheEvaluation(order)"
              class="px-4 py-1.5 border border-gray-400 text-gray-500 rounded-full text-sm"
              custom-class="mx-1!"
            >
              查看评价
            </wd-button>
          </view>
        </view>
      </view>

      <view v-if="isLoading" class="mt-4 flex items-center justify-center py-4">
        <view
          class="w-5 h-5 border-2 border-orange-500 border-t-transparent rounded-full animate-spin mr-2"
        ></view>
        <text class="text-sm text-gray-600">加载更多中...</text>
      </view>

      <view
        v-if="!isLoading && filteredOrders.length > 0 && total == filteredOrders.length"
        class="mt-4 text-center py-4 text-sm text-gray-500"
      >
        — 已经到底啦 —
      </view>
    </view>

    <view
      v-if="cancelModalShow && cancelOrder"
      class="fixed inset-0 bg-black/60 z-40 flex items-center justify-center p-2"
      @click="cancelModalShow = false"
    >
      <view class="bg-white rounded-lg w-full max-w-xs p-2" @click.stop>
        <view class="text-center font-bold text-gray-800 mb-3">确认退款</view>
        <view class="text-center text-gray-600 mb-4 flex flex-col justify-start items-center">
          <text>是否取消订单{{ cancelOrder.orderId }}并退款？</text>
          <text>订单金额￥{{ cancelOrder.totalPrice }}</text>
        </view>
        <view class="flex space-x-3">
          <view
            class="flex-1 py-2 border text-center border-gray-300 text-gray-600 rounded-lg"
            @click="cancelModalShow = false"
          >
            取消
          </view>
          <view
            class="flex-1 py-2 bg-orange-500 text-center text-white rounded-lg"
            @click="confirmOrderRefund"
          >
            确定
          </view>
        </view>
      </view>
    </view>

    <wd-popup v-model="orderCommentShow" :closable="true">
      <view class="w-80 p-4">
        <text class="font-bold mb-2">订单评价</text>
        <wd-form ref="form" :model="orderCommentForm">
          <wd-cell-group :border="true">
            <wd-textarea
              type="textarea"
              label="评价"
              label-width="100px"
              prop="evaluationContent"
              clearable
              v-model="orderCommentForm.evaluationContent"
              placeholder="请输入评价"
              :rules="[{ required: true, message: '请填写评价' }]"
            />
          </wd-cell-group>
          <wd-cell :border="true" label="评价图片">
            <wd-upload
              :file-list="fileList"
              image-mode="aspectFill"
              :action="action"
              @change="handleChange"
              :limit="3"
              name="image"
            />
          </wd-cell>
          <wd-cell :border="true" label="评分">
            <wd-rate v-model="orderCommentForm.evaluationStar" />
          </wd-cell>
          <view class="footer">
            <wd-button type="primary" size="large" @click="handleSubmitComment" block>
              提交
            </wd-button>
          </view>
        </wd-form>
      </view>
    </wd-popup>

    <wd-popup v-model="showOrderDetail" :closable="true" custom-class="bg-black/60 z-40  w-80 p-4">
      <view class="bg-white rounded-lg w-full max-w-md max-h-[90vh] overflow-y-auto" @click.stop>
        <view class="p-4 border-b border-gray-100 flex justify-between items-center">
          <view class="font-bold text-gray-800">订单详情</view>
        </view>
      </view>
      <view class="p-4">
        <view class="mb-4 pb-4 border-b border-gray-100">
          <view class="flex justify-between items-center">
            <text class="text-gray-600">订单类型</text>
            <text
              class="font-medium"
              :class="{
                'text-orange-500': selectedOrder.orderType == '1',
                'text-green-500': selectedOrder.orderType == '2',
                'text-blue-500': selectedOrder.orderType == '3',
                'text-purple-500': selectedOrder.orderType == '4',
              }"
            >
              <text v-if="selectedOrder.orderType == 1">订单</text>
              <text v-if="selectedOrder.orderType == 2">拼团订单</text>
              <text v-if="selectedOrder.orderType == 3">家政订单</text>
              <text v-if="selectedOrder.orderType == 4">转盘订单</text>
            </text>
          </view>

          <view class="flex justify-between items-center">
            <text class="text-gray-600">订单状态</text>
            <text
              class="font-medium"
              :class="{
                'text-orange-500': selectedOrder.status == '0',
                'text-green-500': selectedOrder.status == '1',
                'text-purple-500': selectedOrder.status == '3',
                'text-purple-500': selectedOrder.status == '4',
                'text-gray-500': selectedOrder.status == '5',
              }"
            >
              <!-- {{ selectedOrder.status }} -->
              <text v-if="selectedOrder.status == 0">待付款</text>
              <text v-if="selectedOrder.status == 1">待核销</text>
              <text v-if="selectedOrder.status == 3">待评价</text>
              <text v-if="selectedOrder.status == 4">已完成</text>
              <text v-if="selectedOrder.status == 5">已退款</text>
            </text>
          </view>
        </view>

        <!-- Product Info -->
        <view class="mb-4 pb-4 border-b border-gray-100">
          <view class="flex">
            <image
              :src="selectedOrder.productImage"
              :alt="selectedOrder.productName"
              class="w-20 h-20 object-cover rounded-md"
              @click="openImagePreview(selectedOrder.productImage)"
            />
            <view class="ml-3 flex-1">
              <view class="font-medium text-gray-800">{{ selectedOrder.productName }}</view>
              <view class="mt-1 text-sm w-full flex justify-between text-gray-500">
                <text>¥{{ selectedOrder.totalPrice }}</text>
                <text class="ml-2">x{{ selectedOrder.totalNum }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- Order Info -->
        <view class="space-y-3 text-sm">
          <view class="flex justify-between">
            <text class="text-gray-600">订单编号</text>
            <text class="text-gray-800">{{ selectedOrder.orderId }}</text>
          </view>

          <view class="flex justify-between">
            <text class="text-gray-600">下单时间</text>
            <text class="text-gray-800">{{ selectedOrder.createTime }}</text>
          </view>

          <view v-if="selectedOrder.verificationTime" class="flex justify-between">
            <text class="text-gray-600">核销时间</text>
            <text class="text-gray-800">{{ selectedOrder.verificationTime }}</text>
          </view>

          <view class="flex justify-between">
            <text class="text-gray-600">支付方式</text>
            <text class="text-gray-800" v-if="selectedOrder.channel == '0'">微信支付</text>
            <text class="text-gray-800" v-else-if="selectedOrder.channel == 1">支付宝支付</text>
            <text class="text-gray-800" v-else-if="selectedOrder.channel == 2">转盘赠送</text>
            <text class="text-gray-800" v-else>/</text>
          </view>

          <view class="flex justify-between">
            <text class="text-gray-600">商品金额</text>
            <text class="text-gray-800">¥{{ selectedOrder.totalPrice }}</text>
          </view>

          <view class="flex justify-between font-medium">
            <text class="text-gray-600">实付金额</text>
            <text class="text-orange-500">¥{{ selectedOrder?.payPrice || 0 }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 2">
            <text class="text-gray-600">拼团状态</text>
            <text class="text-orange-500" v-if="selectedOrder?.groupStatus == 1">拼团中</text>
            <text class="text-orange-500" v-if="selectedOrder?.groupStatus == 2">已完成</text>
            <text class="text-orange-500" v-if="selectedOrder?.groupStatus == 3">已取消</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">联系人</text>
            <text class="text-orange-500">{{ selectedOrder?.realName }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">手机号</text>
            <text class="text-orange-500">{{ selectedOrder?.userPhone }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">地址</text>
            <text class="text-orange-500">{{ selectedOrder?.userAddress }}</text>
          </view>

          <view class="flex justify-between font-medium" v-if="selectedOrder.orderType == 3">
            <text class="text-gray-600">上门时间</text>
            <text class="text-orange-500">{{ selectedOrder?.upperTime }}</text>
          </view>
        </view>

        <!-- Order Actions -->
        <view class="mt-6 flex justify-end">
          <!-- <view
            v-if="selectedOrder.status == '1'"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm"
          >
            确认收货
          </view> -->

          <view
            v-if="selectedOrder.status == '3'"
            class="px-4 py-2 bg-orange-500 text-white rounded-lg text-sm"
            @click="openOrderComment(selectedOrder)"
          >
            去评价
          </view>

          <!-- <view class="ml-2 px-4 py-2 border border-gray-300 text-gray-500 rounded-lg text-sm">
            联系客服
          </view> -->

          <wd-button
            class="ml-2 px-4 py-2 border border-gray-300 text-gray-500 rounded-lg text-sm"
            open-type="contact"
          >
            联系客服
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 弹窗 -->
    <wd-popup v-model="verificationPopupShow" :closable="true">
      <view class="w-80 h-80 mt-4 flex flex-col justify-center items-center">
        <text class="mb-1 text-xs text-gray-800">订单{{ selectOrder?.orderId }}核销码</text>
        <text class="mb-1 text-xs text-gray-800">消费请向商家出示</text>
        <canvas class="code-item" canvas-id="qrcode"></canvas>
      </view>
    </wd-popup>

    <wd-popup v-model="checkTheEvaluationShow" :closable="true">
      <view class="bg-white rounded-lg w-full max-w-md max-h-[90vh] overflow-y-auto" @click.stop>
        <view class="p-4 border-b border-gray-100 flex justify-between items-center">
          <view class="font-bold text-gray-800">订单评论</view>
        </view>
      </view>
      <view class="w-80 p-4 flex flex-col" v-if="evaluationData">
        <view class="w-full h-8 text-3.5 mb-2">
          <text class="text-3 text-gray-400">订单编号：</text>
          {{ evaluationData?.orderId }}
        </view>
        <view class="w-full h-8 text-3.5 mb-2">
          <text class="text-3 text-gray-400">评分：</text>
          {{ evaluationData?.evaluationStar }}
        </view>

        <view class="w-full grid grid-cols-3">
          <image
            v-for="(image, index) in parseImage(evaluationData?.evaluationImage)"
            :src="image"
            class="w-full h-20 object-cover rounded-md"
            mode="scaleToFill"
            :key="index"
          />
        </view>
        <view class="mt-2">
          {{ evaluationData?.evaluationContent }}
        </view>

        <view class="mt-2 text-3 text-gray-400">
          {{ evaluationData?.addTime }}
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import UQRCode from 'uqrcodejs'

import { ref, computed, onMounted, onUnmounted } from 'vue'
import { http } from '@/utils/http'

const orderTabs = [
  { label: '全部', status: '' },
  { label: '待付款', status: '0' },
  { label: '待核销', status: '1' },
  { label: '待评价', status: '3' },
  { label: '售后/退款', status: '5' },
]

const setActiveTab = (tabId) => {
  queryParams.value.status = tabId
  queryParams.value.pageNum = 1
  loadMoreOrders()
}

const action = import.meta.env.VITE_SERVER_BASEURL + '/api/file/uploadImage'
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: '',
})

const handleChange = ({ fileList }) => {
  let response = fileList[0].response
  let data = JSON.parse(response)
  if (orderCommentForm.value.evaluationImage == '') {
    orderCommentForm.value.evaluationImage = data.url
    return
  }
  orderCommentForm.value.evaluationImage = orderCommentForm.value.evaluationImage + ',' + data.url
}

const openOrderComment = (order) => {
  orderCommentForm.value.oid = order.id
  orderCommentShow.value = true
}

const fileList = ref([])

const orderCommentShow = ref(false)

const orderCommentForm = ref({
  evaluationContent: '',
  evaluationImage: '',
  evaluationStar: 5,
  oid: '',
})

const handleSubmitComment = async () => {
  let res = await http.post('/api/evaluate/addUserEvaluate', orderCommentForm.value)
  if (res.code == 200) {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
    orderCommentShow.value = false
    queryParams.value.pageNum = 1
    loadMoreOrders()

    uni.pageScrollTo({ scrollTop: 0 })
  }
}

const total = ref(0)

const orders = ref([])
const isLoading = ref(false)

const filteredOrders = computed(() => {
  return orders.value
})

const handlePay = async (order) => {
  let res = await http.get('/api/wxPayApplet/continuePayment', { orderNumber: order.orderId })
  if (res.code == 200) {
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: res.data.timeStamp,
      nonceStr: res.data.nonceStr,
      package: res.data.package,
      signType: 'MD5',
      paySign: res.data.paySign,
      success: (res) => {
        uni.showToast({
          title: '支付成功',
          icon: 'success',
        })

        queryParams.value.pageNum = 1
        loadMoreOrders()
      },
      fail: (err) => {
        uni.showToast({
          title: '支付失败',
          icon: 'none',
        })

        queryParams.value.pageNum = 1
        loadMoreOrders()
      },
    })
  }
}

const parseCanVerification = (order) => {
  if (order.orderType == 2 && order.groupStatus == 2) {
    if (order.status == 1) {
      return true
    }
  } else if (order.orderType == 4 && order.status == 1) {
    return true
  } else if (order.status == 1) {
    return true
  }

  return false
}
// 退款取消
const cancelModalShow = ref(false)
const openCancelOrder = (order) => {
  cancelOrder.value = order
  cancelModalShow.value = true
}
const cancelOrder = ref(null)
const confirmOrderRefund = async () => {
  // 取消订单并退款
}

const parseStatus = (status) => {
  if (status == 0) {
    return '待付款'
  } else if (status == 1) {
    return '待核销'
  } else if (status == 3) {
    return '待评价'
  } else if (status == 4) {
    return '已完成'
  } else if (status == 5) {
    return '售后/退款'
  }
}

const verificationPopupShow = ref(false)
const selectOrder = ref(null)
// show
const system = ref(null)

watch(
  () => verificationPopupShow.value,
  () => {
    if (!verificationPopupShow.value) {
      queryParams.value.pageNum = queryParams.value.pageNum + 1
      loadMoreOrders()
    }
  },
)

const handleVerification = (order) => {
  verificationPopupShow.value = true
  selectOrder.value = order

  system.value = uni.getSystemInfoSync()

  setTimeout(() => {
    // wxcode.qrcode('qrcode', order.orderId, 500, 500)

    // 获取uQRCode实例
    var qr = new UQRCode()
    // 设置二维码内容
    qr.data = order.orderId
    // 设置二维码大小，必须与canvas设置的宽高一致
    qr.size = (system.value.screenWidth / 750) * 500
    // 调用制作二维码方法
    qr.make()
    // 获取canvas上下文
    var canvasContext = uni.createCanvasContext('qrcode', this) // 如果是组件，this必须传入
    // 设置uQRCode实例的canvas上下文
    qr.canvasContext = canvasContext
    // 调用绘制方法将二维码图案绘制到canvas上
    qr.drawCanvas()
  }, 300)
}

onLoad(({ status }) => {
  if (status) {
    queryParams.value.status = status
  }
  loadMoreOrders()
})

onReachBottom(() => {
  if (total.value > orders.value.length) {
    queryParams.value.pageNum = queryParams.value.pageNum + 1
    loadMoreOrders()
  } else {
    uni.showToast({
      title: '没有更多了',
      icon: 'none',
    })
  }
})

const loadMoreOrders = async () => {
  if (isLoading.value) return

  uni.showLoading()

  isLoading.value = true
  try {
    let res = await http.get('/api/home/orders', queryParams.value)
    if (res.code == 200) {
      if (queryParams.value.pageNum == 1) {
        orders.value = res.data.orders
      } else {
        orders.value = [...orders.value, ...res.data.orders]
      }
      total.value = res.data.total
    }
  } catch (error) {
  } finally {
    isLoading.value = false
    uni.hideLoading()
  }
}

const showImagePreview = ref(false)
const previewImage = ref('')

const openImagePreview = (image) => {
  previewImage.value = image
  showImagePreview.value = true
}

const showOrderDetail = ref(false)
const selectedOrder = ref({})

const openOrderDetail = (order) => {
  selectedOrder.value = order
  showOrderDetail.value = true
}

const checkTheEvaluationShow = ref(false)

const evaluationData = ref(null)

const checkTheEvaluation = async (order) => {
  checkTheEvaluationShow.value = true

  let res = await http.post('/api/evaluate/queryOrderId', { orderId: order.orderId })
  if (res.code == 200) {
    evaluationData.value = { ...res.data.evaluate, orderId: order.orderId }
  }
}

const parseImage = (images) => {
  return images.split(',')
}
</script>

<style scoped>
.tab-container {
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
}

.tab-container::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.code-item {
  width: 500rpx;
  height: 500rpx;
}

:deep(.wd-button) {
  margin: 0;
  margin-left: 12rpx;
}
</style>
